define(function (require, exports, module) {

	require("./CommentsAnnot.js");
    require("./AnnotHandleManager.js");

    var annotFactory = WebPDF.AnnotFactory;
    //var annot_PageEventHandler = require('./AnnotPageEvent');

    //var annot_DocViewEventHandler = require('./AnnotDocViewEventHandler');
    var annotMousePtHandler = require('./AnnotMousePtHandler');
    
    require("./AnnotSelectionTool.js");
    var AnnotSelectionToolHandler = WebPDF.Tools.AnnotSelectionToolHandler;

    require("./TextAnnotToolHandler.js");
    var TextAnnotToolHandler = WebPDF.Tools.TextAnnotToolHandler;

    var TypewriterAnnotToolHandler = require("./TypewriterAnnotToolHandler.js");
    
    require("./CommentAnnotToolHandler.js");
    require("./DrawingAnnotToolHandler.js");

    require("../../ImageEngine/PDFAnnotationLoader.js");
    require("../../PDFData/AnnotFactory.js");
    WebPDF.BASEANNOT_PLUGIN_NAME = "BaseAnnotPlugin";

    /**
     * Base annotation plugin
     * @param {WebPDF.ReaderApp} readerApp app instance
     * @extends {WebPDF.IReaderPlugin}
     * @constructor
     */
    var BaseAnnotPlugin = function (readerApp) {
        var _readerApp = readerApp;
        var	_annotHandlerMgr = null,
        	_self = this,
       		_bInited = false,
       		_annotSelectToolHandler = null,
             _textAnnotToolHandler = null;
        //	_bInited = false,
       	//	_pageAnnotCreatedList = {},
       	//	_pageAnnotUpdatedList = [],
       	//	_pageAnnotNeedUpdateList = new Array()

        function _init() {
        	 if (_bInited) return;     
            _bInited = true;             
            
            var docView = _readerApp.getMainView().getDocView();
            var pageCount = docView.getPageCount();
            for (var i = 0;  i < pageCount; i++) {
                var pageView = docView.getPageView(i);
                if(pageView.isPageLoaded()) {
                   _annotHandlerMgr.onPageShowComplete(pageView);
                }
            }
        };       

        this.getPluginName = function () {
            return WebPDF.BASEANNOT_PLUGIN_NAME;
        };

        this.init = function () {           
         
            _annotHandlerMgr = new WebPDF.AnnotHandleManager(_readerApp, _self);            
           
             _annotHandlerMgr.init();
             
            _annotSelectToolHandler = new AnnotSelectionToolHandler(_readerApp,_annotHandlerMgr);
            _readerApp.registerToolHandler(_annotSelectToolHandler);

            _textAnnotToolHandler = new TextAnnotToolHandler(_self);
            _readerApp.registerToolHandler(_textAnnotToolHandler);

            var annotMousePtHandler = new WebPDF.Event.AnnotMousePtHandler(_self);
            _readerApp.registerMousePtHandler(annotMousePtHandler);

            var typewriterAnnotHandler = new TypewriterAnnotToolHandler(_readerApp, WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER,_self);
            _readerApp.registerToolHandler(typewriterAnnotHandler);

            var highlightAnnotHandler = new WebPDF.Event.CommentAnnotToolHandler(_readerApp, WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT);
            _readerApp.registerToolHandler(highlightAnnotHandler);
            
            var underlineAnnotHandler = new WebPDF.Event.CommentAnnotToolHandler(_readerApp, WebPDF.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE);
            _readerApp.registerToolHandler(underlineAnnotHandler);
            
            var inkAnnotToolHandler = new WebPDF.Tools.InkAnnotToolHandler(_readerApp);
            _readerApp.registerToolHandler(inkAnnotToolHandler);
            
            _bindEvents();
            
            
            
            var docView = _readerApp.getMainView().getDocView();
            var visiblePageRange = docView.getVisiblePageRange();
            var jqPagesContainerDiv = $("#" + docView.getDocViewContainerID());
            var docViewDimension = docView.getDocViewDimension();
            var contentPanelHeight = docViewDimension.height;
            var contentPanelWidth = docViewDimension.width;
            var contentPanelOffset = jqPagesContainerDiv.offset();
            for (var i = visiblePageRange.begin; i <= visiblePageRange.end; i++) {
                var pageView = docView.getPageView(i);
                if(pageView.isPageLoaded()) {
                   _annotHandlerMgr.onPageVisible(pageView, contentPanelWidth, contentPanelHeight, contentPanelOffset);
                }
            }
            
            
            jqPagesContainerDiv.on('keydown', function (event) {
                var keyValue = event.keyCode || event.which;
                if (keyValue == 46 ) {
                    _annotHandlerMgr.deleteSelection();
                }
            });
             /*var annotSelectionTool = new WebPDF.Event.AnnotSelectionToolHandler(_readerApp, _annotHandlerMgr);
            _readerApp.registerToolHandler(annotSelectionTool);*/
            var pdfAnnotLoader = new WebPDF.ImageEngine.PDFAnnotationLoader();         
            pdfAnnotLoader.asyncLoadPDFAnnotation(_readerApp,_readerApp.getPDFDoc(), _init,$.noop);
        };

        this.getAnnotationDataToSave = function () {
            var pDocView = _readerApp.getMainView().getDocView();
            var pPDFDoc = pDocView.getPDFDoc();
            var nPageCount = pPDFDoc.getPageCount();
            var annotsToSaveData = [];
            for (var i = 0; i < nPageCount; i++) {
                var pageView = pDocView.getPageView(i);
                if (pageView.isModified()) {
                    //var p = pPDFPage.GetAnnotJsonData();
                    var pageAnnotsDataToSave = {};
                    pageAnnotsDataToSave[WebPDF.PDFData.AnnotDataJSONFormat.pageIndex] = i;
                    var pageAnnotsData = pageView.getPDFPage().getAnnotJsonData(); //[];
                    /* var annotsMap = pPDFPage.GetAnnotsMap();
                    for (var key in annotsMap) {
                    var pAnnot = annotsMap[key];
                    if (pAnnot == null)
                    continue;
                    var annotJsonData = pAnnot.GetAnnotJsonData();
                    pageAnnotsData.push(annotJsonData);
                    }*/
                    pageAnnotsDataToSave[WebPDF.PDFData.AnnotDataJSONFormat.annotations] = pageAnnotsData;
                    annotsToSaveData.push(pageAnnotsDataToSave);
                }
            }
            return annotsToSaveData;
        };
        
        this.getAnnotsData = function () {
        	
 
            $.ajax({
                type: "post",
                url:  _readerApp.getOptions().url+"save",
                data: data,
                dataType: 'json',
                success: function (response) {
                    WebPDF.closeWaiting({});
                    if (response == null) {
                    	WebPDF.alert("", i18n.t("CommonDialog.SaveCommentsFailedMsg"));
                        return;
                    }
                    var msg = "";
                    var error = response.error;
                    if (error != 0) {
                        var checkinPlugin = _preaderApp.GetPluginByName(FXREADER.SPCHECKINOUT_PLUGIN_NAME);
                        var formPlugin = _pReaderApp.GetPluginByName(FXREADER.FORM_PLUGIN_NAME);
                        var bShowRefresh = false;
                        msg = i18n.t("Error.UnknownError") + error;
                        if (failedCallback) {
                            failedCallback(error);
                        }
                        WebPDF.alert("", msg, FXREADER.DialogType.MB_ICONERROR, null, null, bShowRefresh);
                    } else {
                        var len = annotsData.length;
                        var annotDeletedMap = {};
                        for (var i = 0; i < len; i++) {
                            var pageAnnots = annotsData[i];
                            var pageIndex = pageAnnots[WebPDF.PDFData.AnnotDataJSONFormat.pageIndex];
                            var pPDFPage = docView.getPageView(pageIndex).getPDFPage();
                            var annotsMap = pPDFPage.getAnnotsMap();
                            for (var key in annotsMap) {
                                var annot = annotsMap[key];
                                if (annot != null) {
                                    annot.setSourceAnnot(true);
                                }
                                if (!annot.isVisible()) {
                                    annotDeletedMap[key] = 1;
                                    //delete annotsMap[key];
                                }
                            }
                            pPDFPage.deleteAnnots(annotDeletedMap);
                            
                            docView.getPageView(pageIndex).setModified(false);
                        }
                        readerApp.updateVersion(response.version);
                        docView.setModified(false);
//                        _self.SetSaveCommentBtnState(false);
                        if (successCallback != null)
                            successCallback();
//                      FXREADER.TooltipAlert(_Language.CheckInOut.SaveCommentsSuccessfullyMsg, true);
                    }
                }
            });
        };


        this.onAnnotLButtonDown = function (pageView, annot, event) {
            return _annotHandlerMgr.onAnnotLButtonDown(pageView, annot, event);
        };
        this.onAnnotLButtonUp = function (pageView, annot, event){
            return _annotHandlerMgr.onAnnotLButtonUp(pageView, annot, event);
        };
        this.onAnnotLButtonDblClk = function (pageView, annot, event) {
            return _annotHandlerMgr.onAnnotLButtonDblClk(pageView, annot, event);
        };
        this.onAnnotMouseMove = function (pageView, annot, event){
            return _annotHandlerMgr.onAnnotMouseMove(pageView, annot, event);
        };
        this.onAnnotMouseOver = function (pageView, annot, event){
            return _annotHandlerMgr.onAnnotMouseOver(pageView, annot, event);
        };
        this.onAnnotMouseLeave = function (pageView, annot, event) {
            return _annotHandlerMgr.onAnnotMouseLeave(pageView, annot, event);
        };

        function _bindEvents(){
        	
            var docView = _readerApp.getMainView().getDocView();
            $(readerApp).on(WebPDF.EventList.DOCVIEW_ZOOM_CHANGED,function(event,data){
                _annotHandlerMgr.onDocViewZoom(data.newScale);
             }).on(WebPDF.EventList.DOCVIEW_RESIZE, function(){
                _annotHandlerMgr.onDocViewResize();
            }).on(WebPDF.EventList.DOCVIEW_PRE_RESIZE, function(){
                _annotHandlerMgr.onPreDocViewResize();
            }).on(WebPDF.EventList.DOCVIEW_SCROLL,function(){
                _annotHandlerMgr.onDocViewScroll();
            }).on(WebPDF.EventList.PAGE_INVISIBLE, function(event,data){
                for(var i=0; i<data.pages.length; i++){
                    _annotHandlerMgr.onPageInvisible(docView.getPageView(data.pages[i]));
                }
            }).on(WebPDF.EventList.PAGE_SHOW_COMPLETE,function(event,data){
                _annotHandlerMgr.onPageShowComplete(data.pageView);
            }).on(WebPDF.EventList.PAGE_VISIBLE, function(event,data){
                for(var i=0; i<data.pages.length; i++){
                    _annotHandlerMgr.onPageVisible(docView.getPageView(data.pages[i]), data.contentPanelWidth, data.contentPaneHeight,
                        data.contentPanelOffset, false);
                }
            });
        }

        this.onRegister = function () {
        };

        this.unload = function () {
        };

        this.getReaderApp = function(){
            return _readerApp;
        };

        this.registerAnnotHandler = function (annotHandler) {
            _annotHandlerMgr.registerAnnotHandler(annotHandler);
        };

        /**
         * Get annotation handler manager
         * @returns {WebPDF.AnnotHandleManager}
         */
        this.getAnnotHandlerMgr = function () {
            return _annotHandlerMgr;
        };
    };

    BaseAnnotPlugin.createPlugin = function(readerApp){
        return new BaseAnnotPlugin(readerApp);
    }
    module.exports = BaseAnnotPlugin;   
});